#include "StdAfx.h"
#include "Filer.h"

Filer::Filer(void)
{
	misopen = false;
	mfn = "";
}

Filer::~Filer(void)
{
	Close();
}

int Filer::Write( unsigned char * buf, int len)
{
	if( misopen )
	{
		mfile.Write( buf, len );
		return 1;
	}
	else
	{
		return -1;
	}
}
void Filer::writeLine(CString cs)
{
	if (misopen)
	{
		mfile.WriteString( cs);
		mfile.WriteString(TEXT("\r\n"));
	}
}
int Filer::OpenFileByTime(CString dir, CString tail, int mode )
{
	int d = -1;

	CTime t = CTime::GetCurrentTime();
	CString fn;
	fn.Format( TEXT("%02d%02d%02d%02d%02d"), t.GetMonth(), t.GetDay(), 
		t.GetHour(), t.GetMinute(), t.GetSecond());
	fn = dir + _T("\\") + fn + tail;
	if( ( mfn.Compare( fn ) ) )
	{	// different;
		d = Open( fn, mode );
		if( d < 0 )
		{
			Close();
			return d;
		}
	}
	else
	{
		d = 1;
	}
	return d;
}
int	Filer::OpenRead( CString fn, int mode )
{
	Close();
	BOOL isok;
	switch( mode )
	{
	case 0:
		isok = mfile.Open( fn, CFile::typeBinary | CFile::modeRead );
		break;
	case 1:
		isok = mfile.Open( fn, CFile::typeText | CFile::modeRead );
		break;

	default :
		isok = FALSE;
		break;
	}
	if( isok )
	{
		misopen = true;
		mfn = fn;

		return 1;
	}
	else
	{
		misopen = false;
		mfn = "";

		return -1;
	}
}

int Filer::Open(CString fn, int mode )
{
	Close();

	BOOL isok;
	switch( mode )
	{
	case 0:	// bin, append;
		isok = mfile.Open( fn, CFile::typeBinary | CFile::modeCreate 
			| CFile::modeNoTruncate | CFile::modeReadWrite );
		break;
	case 1:	// bin, create;
		isok = mfile.Open( fn, CFile::typeBinary | CFile::modeCreate 
			| CFile::modeReadWrite );
		break;
	case 2:	// txt, append;
		isok = mfile.Open( fn, CFile::typeText | CFile::modeCreate 
			| CFile::modeNoTruncate | CFile::modeReadWrite );
		break;
	case 3:	// txt, create;
		isok = mfile.Open( fn, CFile::typeText | CFile::modeCreate 
			| CFile::modeReadWrite );
		break;
	case 5: // bin, read;
		isok = mfile.Open( fn, CFile::typeBinary | CFile::modeRead );
		break;
	case 6: // txt, read;
		isok = mfile.Open( fn, CFile::typeText | CFile::modeRead );
		break;
	default :
		isok = FALSE;
		break;
	}
	if( isok )
	{
		misopen = true;
		mfn = fn;

		//mfile.SeekToEnd();
		return 1;
	}
	else
	{
		misopen = false;
		mfn = "";

		return -1;
	}
}

void Filer::Close( void)
{
	if( misopen )
	{
		mfile.Close();
		misopen = false;
		mfn = "";
	}
}

CString Filer::GetCurtimeStr()
{
	CTime t = CTime::GetCurrentTime();
	CString fn;
	fn.Format( TEXT("%02d%02d%02d%02d%02d"), t.GetMonth(), t.GetDay(), 
		t.GetHour(), t.GetMinute(), t.GetSecond());
	return fn;

}